import UserController from '@/services/user';
import { IUser } from '@/types/user';
import { formatDate } from '@/utils/tools';
import { PlusOutlined } from '@ant-design/icons';
import {
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import {
  Badge,
  Button,
  Descriptions,
  Image,
  message,
  Modal,
  Popconfirm,
  Switch,
} from 'antd';
import React, { useRef, useState } from 'react';
import { Access, useAccess } from 'umi';

const UserList: React.FC = () => {
  // 首先需要维护一组分页相关的数据
  // 这个分页数据回头是会被作为参数一起发送到服务器的
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
  });
  // 控制修改面板开启的状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 用户详情信息
  const [userInfo, setUserInfo] = useState<IUser>();
  // 展示
  const tableRef = useRef<any>();
  const navigate = useNavigate();
  const access = useAccess();

  /**
   * 分页组件发生修改时会调用此回调函数
   */
  function handlePageChange(current: number, pageSize: number) {
    setPagination({
      current,
      pageSize,
    });
  }
  /**
   * 删除对应的回调
   */
  function handleDelete(userInfo: IUser) {
    // 直接在这里发送请求，不需要通过状态仓库
    UserController.deleteUser(userInfo._id);
    // 删除之后需要强制刷新一个表格
    tableRef.current.reload();
    message.success('删除用户成功');
  }
  /**
   * 切换用户的可用状态
   */
  function switchChange(row: IUser, value: boolean) {
    UserController.editUser(row._id, { ...row, enabled: value });
    if (value) {
      message.success('用户状态已激活');
    } else {
      message.success('用户已禁用');
    }
  }
  async function handleOpenModel(userid: string) {
    const { data } = await UserController.getUserById(userid);
    setUserInfo(data);
    setIsModalOpen(true);
  }
  /**
   * 点击面板取消按钮时关闭该面板
   */
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns: ProColumns<IUser, string>[] = [
    {
      title: '序号',
      align: 'center',
      width: 50,
      search: false,
      render: (text, record, index) => {
        return (pagination.current - 1) * pagination.pageSize + index + 1;
      },
    },
    {
      title: '登录账号',
      dataIndex: 'loginId',
      key: 'loginId',
      align: 'center',
    },
    // {
    //   title: '登录密码',
    //   dataIndex: 'loginPwd',
    //   key: 'loginPwd',
    //   align: 'center',
    //   search: false,
    // },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
    },
    {
      title: '积分',
      dataIndex: 'points',
      key: 'points',
      align: 'center',
      search: false,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      valueType: 'image',
      align: 'center',
      search: false,
    },
    {
      title: '账号状态',
      dataIndex: 'enabled',
      key: 'enabled',
      align: 'center',
      search: false,
      render: (_, row) => {
        const defaultChecked = row.enabled ? true : false;
        return [
          <Switch
            key={row._id}
            defaultChecked={defaultChecked}
            size="small"
            onChange={(value) => switchChange(row, value)}
          />,
        ];
      },
    },
    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      fixed: 'right',
      align: 'center',
      render: (_, row) => {
        return (
          <div>
            <Button
              type="link"
              size="small"
              onClick={() => handleOpenModel(row._id)}
            >
              详情
            </Button>
            <Button
              type="link"
              size="small"
              onClick={() => navigate(`/user/edit-user/${row._id}`)}
            >
              编辑
            </Button>
            <Access accessible={access.SuperAdmin}>
              <Popconfirm
                title="你确定要删除么？"
                onConfirm={() => handleDelete(row)}
                okText="删除"
                cancelText="取消"
              >
                <Button type="link" size="small" danger>
                  删除
                </Button>
              </Popconfirm>
            </Access>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <PageContainer>
        <ProTable
          headerTitle={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/user/add-user')}
            >
              添加
            </Button>
          }
          actionRef={tableRef}
          columns={columns}
          rowKey={(row) => row._id}
          pagination={{
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [5, 10, 15, 20],
            ...pagination,
            onChange: handlePageChange,
          }}
          request={async (params) => {
            // console.log(params, 'params');
            const result = await UserController.getUserByPage(params);
            return {
              data: result.data.data,
              success: !result.code,
              total: result.data.count,
            };
          }}
        />
      </PageContainer>
      {/* 详情面板 */}
      <Modal
        title="用户详情"
        width="600px"
        open={isModalOpen}
        style={{ top: '50px' }}
        footer={false}
        onCancel={handleCancel}
      >
        <Descriptions layout="vertical">
          <Descriptions.Item label="头像">
            <Image src={userInfo?.avatar} width={100} />
          </Descriptions.Item>
          <Descriptions.Item label="用户昵称">
            {userInfo?.nickname}
          </Descriptions.Item>
          <Descriptions.Item label="登录账号">
            {userInfo?.loginId}
          </Descriptions.Item>
          <Descriptions.Item label="账号状态" span={2}>
            <Badge
              status={userInfo?.enabled ? 'processing' : 'error'}
              text={userInfo?.enabled ? '可用' : '已冻结'}
            />
          </Descriptions.Item>
          <Descriptions.Item label="用户积分" span={2}>
            {userInfo?.points}
          </Descriptions.Item>

          <Descriptions.Item label="注册时间" span={2}>
            {formatDate(userInfo?.registerDate)}
          </Descriptions.Item>
          <Descriptions.Item label="上次登录时间" span={2}>
            {formatDate(userInfo?.lastLoginDate)}
          </Descriptions.Item>

          <Descriptions.Item label="个人简介" span={3}>
            {userInfo?.intro ? userInfo?.intro : '未填写'}
          </Descriptions.Item>

          <Descriptions.Item label="邮箱">
            {userInfo?.mail ? userInfo?.mail : '未填写'}
          </Descriptions.Item>
          <Descriptions.Item label="QQ号">
            {userInfo?.qq ? userInfo?.qq : '未填写'}
          </Descriptions.Item>
          <Descriptions.Item label="微信号">
            {userInfo?.wechat ? userInfo?.wechat : '未填写'}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
    </div>
  );
};

export default UserList;
